package com.appspot.moviesessions;

import java.io.FileNotFoundException;
import java.io.InputStream;

import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.drawable.BitmapDrawable;
import android.net.Uri;
import android.os.Bundle;
import android.support.v4.app.FragmentActivity;
import android.support.v4.app.LoaderManager.LoaderCallbacks;
import android.support.v4.content.CursorLoader;
import android.support.v4.content.Loader;
import android.support.v4.widget.CursorAdapter;
import android.support.v4.widget.SimpleCursorAdapter.ViewBinder;
import android.view.View;
import android.widget.ListView;
import android.widget.TextView;

import com.appspot.moviesessions.provider.MovieSession;

public class StartActivity extends FragmentActivity implements
        LoaderCallbacks<Cursor> {
	private static final int SESSION_LOADER = 0x01;
	private android.support.v4.widget.SimpleCursorAdapter cursorAdapter;

	/** Called when the activity is first created. */
	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.main);
	}

	@Override
	protected void onStart() {
		super.onStart();

		final ListView searchList = (ListView) findViewById(R.id.movie_list);

		getSupportLoaderManager().initLoader(SESSION_LOADER, null, this);

		cursorAdapter = new android.support.v4.widget.SimpleCursorAdapter(this,
		        R.layout.movie, null,
		        new String[] { MovieSession.Movie.POSTER_URI },
		        new int[] { R.id.movie_poster },
		        CursorAdapter.FLAG_REGISTER_CONTENT_OBSERVER);

		ViewBinder savb = new ViewBinder() {
			@Override
			public boolean setViewValue(View view, Cursor cursor, int i) {

			
				InputStream thumbStream;
				try {
					thumbStream = getContentResolver().openInputStream(
					        Uri.parse(cursor.getString(i)));
					Bitmap bm = BitmapFactory.decodeStream(thumbStream);
					TextView tv = (TextView) view;
					BitmapDrawable bitmapDrawable = new BitmapDrawable(bm);
					tv.setCompoundDrawablesWithIntrinsicBounds(bitmapDrawable, null, null, null);
					tv.setText(" "+cursor.getString(1));
				} catch (FileNotFoundException e) {
					e.printStackTrace();
				}
				return true;
			}
		};

		cursorAdapter.setViewBinder(savb);

		searchList.setAdapter(cursorAdapter);
	}

	@Override
	public Loader<Cursor> onCreateLoader(int arg0, Bundle arg1) {
		return new CursorLoader(getApplicationContext(),
		        MovieSession.CONTENT_URI,
		        new String[] { MovieSession.Movie._ID,MovieSession.Movie.NAME,
		                MovieSession.Movie.POSTER_URI }, null, null, null);
	}

	@Override
	public void onLoadFinished(Loader<Cursor> arg0, Cursor cursor) {
		cursorAdapter.swapCursor(cursor);

	}

	@Override
	public void onLoaderReset(Loader<Cursor> arg0) {
		cursorAdapter.swapCursor(null);

	}

}